package com.menu.Configuration.Security;

import com.menu.Configuration.Filter.TokenAuthFilter;
import com.menu.Configuration.Filter.TokenLoginFilter;
import com.menu.Service.UserService;
import com.menu.Utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private TokenManager tokenManager;
    @Qualifier("userDetailsImpl")
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/swagger-ui/**",
                        "/webjars/**",
                        "/swagger-resources/**",
                        "/v3/**",
                        "/Visitor/**",
                        "/Static/**",
                        "/Alipay/**").permitAll();
        http.exceptionHandling()
                //没有权限访问
                .authenticationEntryPoint(new UnauthEntryPoint())
                .accessDeniedHandler(new SimpleAccessDeniedHandler())
                .and().csrf().disable()
                .authorizeRequests()
                .antMatchers("/Admin/**").hasAnyRole("1")
                .antMatchers("/User/**").hasAnyRole("1","0")
                .anyRequest().authenticated()
                .and()
                .addFilter(new TokenLoginFilter(tokenManager, authenticationManager()))
                .addFilter(new TokenAuthFilter(authenticationManager(), tokenManager,redisUtil));
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder);
    }

    /**
     * 密码加密对象
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
